<?php

namespace app\admin\controller\test\mbti;

use app\admin\model\test\mbti\Cate as mbtiCate;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\TestMbtiAnswer;
use PhpOffice\PhpWord\PhpWord;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Answer extends Backend
{
    
    /**
     * Answer模型对象
     * @var \app\admin\model\test\mbti\Answer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\test\mbti\Answer;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function info($ids = null){
        $row = TestMbtiAnswer::get($ids);
        $cates = mbtiCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }

        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'count' => $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向'
        ];
        $i = [
            'count' => $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向'
        ];
        $n = [
            'count' => $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉'
        ];
        $s = [
            'count' => $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉'
        ];
        $t = [
            'count' => $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考'
        ];
        $f = [
            'count' => $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感'
        ];
        $j = [
            'count' => $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断'
        ];
        $p = [
            'count' => $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        $this -> assignconfig('ret_arr',$retArr);
        $this -> assign('ret_arr',$retArr);
        $this -> assign('ret',$str);
        $this -> assign('cates',$cs);
        if($row -> imgs){
            $img = unserialize($row -> imgs);
            $this -> assign('img',$img);
        }
        return $this -> fetch();
    }

    public function download($ids = null){
        $row = TestMbtiAnswer::get($ids);
        $cates = mbtiCate::all();
        $cs = [];
        foreach ($cates as $k => $v){
            $cs[$v['cate']] = $v['desc'];
        }

        $answers_ana = unserialize($row->answers_ana);

        $ae = isset($answers_ana['e']) ? $answers_ana['e'] : 0;
        $ai = isset($answers_ana['i']) ? $answers_ana['i'] : 0;
        $an = isset($answers_ana['n']) ? $answers_ana['n'] : 0;
        $as = isset($answers_ana['s']) ? $answers_ana['s'] : 0;
        $at = isset($answers_ana['t']) ? $answers_ana['t'] : 0;
        $af = isset($answers_ana['f']) ? $answers_ana['f'] : 0;
        $aj = isset($answers_ana['j']) ? $answers_ana['j'] : 0;
        $ap = isset($answers_ana['p']) ? $answers_ana['p'] : 0;

        $e = [
            'count' => $ae,
            'percent'   => round($ae/($ae+$ai),2),
            'name'  => '外向'
        ];
        $i = [
            'count' => $ai,
            'percent'   => 1- $e['percent'],
            'name'  => '内向'
        ];
        $n = [
            'count' => $an,
            'percent'   => round($an/($an+$as),2),
            'name'  => '直觉'
        ];
        $s = [
            'count' => $as,
            'percent'   => 1-$n['percent'],
            'name'  => '感觉'
        ];
        $t = [
            'count' => $at,
            'percent'   => round($at/($at+$af),2),
            'name'  => '思考'
        ];
        $f = [
            'count' => $af,
            'percent'   => 1-$t['percent'],
            'name'  => '情感'
        ];
        $j = [
            'count' => $aj,
            'percent'   => round($aj/($aj+$ap),2),
            'name'  => '判断'
        ];
        $p = [
            'count' => $ap,
            'percent'   => 1 - $j['percent'],
            'name'  => '感知'
        ];

        $str = '';
        if($ai>=$ae){
            $str .= 'i';
        }else{
            $str .= 'e';
        }
        if($an>=$as){
            $str .= 'n';
        }else{
            $str .= 's';
        }

        if($af>=$at){
            $str .= 'f';
        }else{
            $str .= 't';
        }

        if($ap>=$aj){
            $str .= 'p';
        }else{
            $str .= 'j';
        }

        $retArr = [
            'e' => $e,
            'i' => $i,
            'n' => $n,
            's' => $s,
            'j' => $j,
            'p' => $p,
            'f' => $f,
            't' => $t
        ];
        if($row -> imgs){
            $img = unserialize($row -> imgs);
        }




        $languageEnGb = new \PhpOffice\PhpWord\Style\Language(\PhpOffice\PhpWord\Style\Language::ZH_CN);

        $phpWord = new \PhpOffice\PhpWord\PhpWord();
        $phpWord->getSettings()->setThemeFontLang($languageEnGb);

		$sectionX = $phpWord->addSection([
		      'pageSizeH' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(12.7),
		      'pageSizeW' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(8.3)
		]);
		$imgUrl = ROOT_PATH.'public/assets/img/water1.png'; //获取封面URL地址
		$botImgUrl = ROOT_PATH.'public/assets/img/water4.png';
		
//		$sectionX->addImage(
//		    $imgUrl,
//		    array(
//		        'width' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(2.677)),
//		        'height' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(1.177)),
//		        'positioning' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'posHorizontal' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'posVertical' => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//			   'marginRight' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//			   'marginTop' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//			   'wrappingStyle' => 'infront'
//		    )
//		);
//		$sectionX->addImage(
//		    $botImgUrl,
//		    array(
//		       'width' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(16)),
//		       'height' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(7.6)),
//		        'positioning'      => \PhpOffice\PhpWord\Style\Image::POSITION_ABSOLUTE,
//		        'posHorizontal'    => \PhpOffice\PhpWord\Style\Image::POSITION_HORIZONTAL_CENTER,
//		        'posHorizontalRel' => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
//		        'posVerticalRel'   => \PhpOffice\PhpWord\Style\Image::POSITION_RELATIVE_TO_PAGE,
//		        'marginRight' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//		        'marginBottom' => round(\PhpOffice\PhpWord\Shared\Converter::cmToPixel(0)),
//		        'posVertical'      => \PhpOffice\PhpWord\Style\Image::POSITION_VERTICAL_BOTTOM,
//		    )
//		);
		//标题
		$sectionX-> addText('测评报告',
		   [
		           'size'    => 60,
		           'bold' => true,
		           'name'=>'黑体',
		           'color'=>'#0674bc',
		       ],[
		           'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
		           'spaceAfter'  => 0,                                                   //标题后部预留长度
		           'spaceBefore' => 3550,                                                    //标题前部预留长度
		       ]
		);
		$sectionX-> addText('Talent Evaluation Report',
		   [
		           'size'    => 20,
		           'bold' => false,
		           'name'=>'黑体',
		           'color'=>'#0674bc',
		       ],[
		           'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
		           'spaceAfter'  => 0,                                                   //标题后部预留长度
		           'spaceBefore' => 70,                                                    //标题前部预留长度
		       ]
		);
        $section = $phpWord->addSection([
            	'pageSizeH' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(12.7),
        	    'pageSizeW' => \PhpOffice\PhpWord\Shared\Converter::inchToTwip(8.3)
        ]);
        $paragraphStyleName = 'pStyle';
        $phpWord->addParagraphStyle($paragraphStyleName, array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,'spaceAfter' => 300,'spaceBefore' => 500));
        $fontStyleName = 'rStyle';
        $phpWord->addFontStyle($fontStyleName, array('name'=>'黑体', 'size' => 16, 'allCaps' => true));
        $section -> addText('MBTI 倾向示意图（你更倾向于：'.strtoupper($str).' 型）',[
                'size'    => 18,
                'bold' => true,
                'name'=>'黑体',
                'color'=>'black'
            ],[
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 500,                                                   //标题后部预留长度
                'spaceBefore' => 500,                                                    //标题前部预留长度
            ]);



        if(isset($img)){
            $imgcount = count($img);
            foreach ($img as $ig){
                $imgpath = $_SERVER['DOCUMENT_ROOT'].$ig;
                if(!is_file($imgpath)) continue;
                $info = getimagesize($imgpath);
                $oheight = $height = $info[1];
                $owidth = $width = $info[0];
                if($imgcount == 1){
                    $width = min($width,300);
                    $height = intval($oheight * ($width/$owidth));
                }
                $section->addImage($_SERVER['DOCUMENT_ROOT'].$ig, array('width'=>$width, 'height'=>$height,'alignment'=> \PhpOffice\PhpWord\SimpleType\Jc::CENTER));
            }
        }

        // $section -> addText('MBTI 测评得分占比',[
        //         'size'    => 16,
        //         'name'=>'黑体',
        //         'color'=>'black'
        //     ],[
        //         'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
        //         'spaceAfter'  => 300,                                                   //标题后部预留长度
        //         'spaceBefore' => 500,                                                    //标题前部预留长度
        //     ]);


        $tr1 = [];
        $tr2 = [];
        $tr3 = [];


        $arr = ['e','i','s','n','t','f','j','p'];
        foreach($arr as $vv){
            foreach($retArr as $k => $v){
                if($k == $vv){
                    $tr1[] = $v['name'].' '.strtoupper($k);
                    $tr2[] = $v['count'];
                    $tr3[] = ($v['percent']*100).'%';
                }
            }
        }


        $section->addTextBreak(1);
        $fancyTableStyleName = 'Fancy Table';
        $fancyTableStyle = array('borderSize' => 1, 'borderColor' => '000000', 'cellMargin' => 80, 'alignment' => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER, 'cellSpacing' => 0);
        $fancyTableFirstRowStyle = array('borderBottomSize' => 18, 'borderBottomColor' => '000000', 'bgColor' => '000000');
        $fancyTableCellStyle = array('valign' => 'center');
        $fancyTableFontStyle = array('bold' => true);
        $phpWord->addTableStyle($fancyTableStyleName, $fancyTableStyle, $fancyTableFirstRowStyle);
        $table = $section->addTable($fancyTableStyleName);


        // for ($r = 1; $r <= 3; $r++) {
        //     $table->addRow();
        //     if($r == 1){
        //         foreach ($tr1 as $v){
        //             $table->addCell(1050, $fancyTableCellStyle)->addText($v, $fancyTableFontStyle);
        //         }
        //     }
        //     if($r == 2){
        //         foreach ($tr2 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        //     if($r == 3){
        //         foreach ($tr3 as $v){
        //             $table->addCell(1050)->addText($v);
        //         }
        //     }
        // }

        $section -> addText('MBTI 测评结果分析',[
                'size'    => 16,
                'name'=>'黑体',
                'color'=>'black'
            ],[
                'alignment'   => \PhpOffice\PhpWord\SimpleType\Jc::CENTER,              //居中校准
                'spaceAfter'  => 500,                                                   //标题后部预留长度
                'spaceBefore' => 500,                                                    //标题前部预留长度
            ]);

        $html = str_replace(array("<br>","'","<o:p>","</o:p>","&quot;",'calibri=""','light";=""','font-size:=""','16pt;"=""'),'',$cs[$str]);
        $html = str_replace('你的类型是：','你的类型是：'.strtoupper($str),$html);
        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);



        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

        $user = User::get($row -> user_id);
        $file_name = 'uploads/MBTI-'.$user['mobile'].'-'.(rand(1111,9999)).'.docx';

        $objWriter->save($file_name);


        //以只读和二进制模式打开文件
        $file = fopen ( $file_name, "rb" );

        //告诉浏览器这是一个文件流格式的文件
        Header ( "Content-type: application/octet-stream" );
        //请求范围的度量单位
        Header ( "Accept-Ranges: bytes" );
        //Content-Length是指定包含于请求或响应中数据的字节长度
        Header ( "Accept-Length: " . filesize ( $file_name ) );
        //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
        Header ( "Content-Disposition: attachment; filename=" . 'MBTI-'.$user['nickname'].'-'.(rand(1111,9999)).'.docx' );

        //读取文件内容并直接输出到浏览器
        echo fread ( $file, filesize ( $file_name ) );
        fclose ( $file );
        exit ();
    }
}
